<template>
  <div class="search-container">
    <!-- 搜索栏》事件监听 -->
    <form action="/" class='header-search'>
      <van-search background="#4fc08d" v-model="searchText" show-action placeholder="请输入搜索关键词" @search="onSearch"
        @cancel="$router.go(-1)" @focus='isResult = false' />
    </form>
    <searchResults v-if="isResult" :searchText='searchText' />
    <searchSuggestion v-else-if='searchText' :searchText='searchText' @changeStr='onSearch' />
    <SearchHistory v-else :searchHistories='searchHistories' @changeStr='onSearch' @deleteOneList='deleteOneList'
      @clearAll='searchHistories = []' />
  </div>
</template>

<script>
import SearchHistory from './components/search-history.vue'
import searchSuggestion from './components/search-suggestion.vue'
import searchResults from './components/search-results.vue'
import { setItem, getItem } from '@/utils/seccession.js'
export default {
  name: 'search-container',
  data () {
    return {
      searchText: '',
      isResult: false,
      searchHistories: getItem('HISTORY') || []
    }
  },
  components: { SearchHistory, searchSuggestion, searchResults },
  created () {

  },

  methods: {
    deleteOneList (index) {
      this.searchHistories.splice(index, 1)
    },
    onSearch (str) {
      this.searchText = str
      this.searchHistories.unshift(str)
      this.searchHistories = [...new Set(this.searchHistories)]
      // if (this.searchHistories.indexOf(str) === -1) this.searchHistories.unshift(str)
      this.isResult = true
    }
  },
  watch: {
    searchHistories (arr) {
      setItem('HISTORY', arr)
    }
  }
}
</script>

<style scoped lang='less'>
.search-container {
  .header-search {
    position: sticky;
    top: 0;
    z-index: 9;
  }
  .van-search {
    .van-search__action {
      color: #fff;
    }
  }
}
</style>
